<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 使用绝对路径包含文件
require_once dirname(__DIR__) . '/config/database.php';
require_once dirname(__DIR__) . '/utils/encryption.php';

$db = new Database();
$conn = $db->getConnection();
$encryption = new Encryption();

// 获取请求参数
$data = json_decode(file_get_contents('php://input'), true);
$device_id = null;

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // 从查询参数获取 device_id
    $device_id = isset($_GET['device_id']) ? $_GET['device_id'] : null;
    
    //写入日志文件
    file_put_contents('log.txt', "GET request - device_id: " . $device_id . "\n", FILE_APPEND);
    
    // 处理GET请求 - 返回服务器上的数据
    try {
        if (!$device_id) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Device ID is required'
            ]);
            exit;
        }
        //检查$device_id是否存在,如果存在则查询用户表是否存在
        $stmt = $conn->prepare("SELECT * FROM users WHERE device_id = ?");
        $stmt->execute([$device_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!$result){
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Device ID not found'
            ]);
            exit;
        }

        $stmt = $conn->prepare("SELECT data FROM sync_data WHERE device_id = ? ORDER BY updated_at DESC LIMIT 1");
        $stmt->execute([$device_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($result) {
            echo json_encode([
                'success' => true,
                'data' => $result['data']
            ]);
        } else {
            echo json_encode([
                'success' => true,
                'data' => null
            ]);
        }
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Database error: ' . $e->getMessage()
        ]);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理POST请求 - 保存新数据
    $device_id = isset($data['device_id']) ? $data['device_id'] : null;
    
    if (!$device_id) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Device ID is required'
        ]);
        exit;
    }
    //检查$device_id是否存在,如果存在则查询用户表是否存在
    $stmt = $conn->prepare("SELECT * FROM users WHERE device_id = ?");
    $stmt->execute([$device_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if(!$result){
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Device ID not found'
        ]);
        exit;
    }
    //'add': 新增记录'update': 更新记录'delete': 删除记录
    try {
        //如果是新增
        if($data['operation'] == 'add'){
            //检查是否存在旧数据,如果存在则写入旧版本记录sync_logs
            $stmt = $conn->prepare("SELECT data FROM sync_data WHERE device_id = ?");
            $stmt->execute([$device_id]);
            $oldData = $stmt->fetch(PDO::FETCH_ASSOC);
            if($oldData){
                //写入旧版本记录sync_logs
                $stmt = $conn->prepare("INSERT INTO sync_logs (device_id, data, created_at) VALUES (?, ?, NOW())");
                $stmt->execute([$device_id, $oldData['data']]);
            }
        }
        if($data['operation'] == 'update'){
            // 检查是否存在旧数据
            $stmt = $conn->prepare("SELECT data FROM sync_data WHERE device_id = ?");
            $stmt->execute([$device_id]);
            $oldData = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($oldData) {
                // 更新现有数据
                $stmt = $conn->prepare("UPDATE sync_data SET data = ?, updated_at = NOW() WHERE device_id = ?");
                $stmt->execute([$data['data'], $device_id]);
            } else {
                // 插入新数据
                $stmt = $conn->prepare("INSERT INTO sync_data (device_id, data, created_at, updated_at) VALUES (?, ?, NOW(), NOW())");
                $stmt->execute([$device_id, $data['data']]);
            }
        }
        if($data['operation'] == 'delete'){
            // 检查是否存在旧数据
            $stmt = $conn->prepare("SELECT data FROM sync_data WHERE device_id = ?");
            $stmt->execute([$device_id]);
            $oldData = $stmt->fetch(PDO::FETCH_ASSOC);
            if($oldData){
                //写入旧版本记录sync_logs
                $stmt = $conn->prepare("INSERT INTO sync_logs (device_id, data, created_at) VALUES (?, ?, NOW())");
                $stmt->execute([$device_id, $oldData['data']]);
            }
            //删除数据
            $stmt = $conn->prepare("DELETE FROM sync_data WHERE device_id = ?");
            $stmt->execute([$device_id]);
        }

        

        echo json_encode([
            'success' => true,
            'message' => 'Data synchronized successfully'
        ]);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Database error: ' . $e->getMessage()
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'error' => 'Method not allowed'
    ]);
}
?> 